# -*- coding:utf-8 -*-
from tkinter import *
from flask import *
import os,json
import tkinter as tk  # 使用Tkinter前需要先导入
import tkinter.font as tf
import threading
import tkinter.messagebox
import logging
from flask_cors import *
import os
import exifread

app = Flask(__name__)
app.config.from_object(__name__)

# # 接口文档样式
# # 需要显示文档的 Api
#原来
# from flask_docs import ApiDoc
#修改后
# from api_doc import ApiDoc

# app.config['API_DOC_MEMBER'] = ['api']
# 需要排除的 RESTful Api 文档
# app.config['RESTFUL_API_DOC_EXCLUDE'] = []
# api = Blueprint('api', __name__)
# ApiDoc(app)

CORS(app, resources=r'/*')

#禁用控制台
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

def response_return(code, msg, data):
    """[summary]
    Args:
        code ([type]): 200(请求成功),404(请求失败),500(服务器出错)
        msg ([type]): msg
        data ([type]): json_data
    Returns:
        [type]: [description]
    """
    if data == None:
        data = []
    return json.dumps({'code': code, 'msg': msg, 'data': list(data)}, ensure_ascii=False)

def write_error(e):
    """[summary]
    Args:
        e ([type]): [description]
    """
    with open('error.txt', 'a') as file_handle:
        file_handle.write("error: %s--%s" %
                          (e.__traceback__.tb_lineno, str(e)))  # 写入
        file_handle.write('\n')
        
@app.route('/', methods=['get','post'])
def index():
    try:
        #放入待读取图片GPS信息的全部图片
        filepath="./img_gps_show/static/img/" 
        data_new_map=[]
        FileName,FileNameWithPath,FileDir = GetNameByEveryDir(filepath)
        for i in range(len(FileNameWithPath)):
            a={}
            info=exifImage(FileNameWithPath[i])
            if info:
                a['time']=info[0]
                a["lng"]=info[1]
                a['lat']=info[2]
                a['filename']=FileName[i]
                data_new_map.append(a)
            else:
                print("该图没有GPS信息：%s"%FileNameWithPath[i])  
        # 按时间排序
        data_new_map = sorted(data_new_map, key = lambda x: x["time"])
        print(data_new_map)
        return render_template("index.html",data_new_map=json.dumps(data_new_map))
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)
    
def run_sever():
    app.run(host='0.0.0.0',port=5000,debug=True,use_reloader=False)
    
def start():
    global l,chiose
    if chiose==0:
        thre = threading.Thread(target=run_sever)   # 创建一个线程运行服务器
        thre.setDaemon(True)
        thre.start()  # 运行线程    
        chiose=1
        l["text"]="演示地址\n鼠标左键点开查看：\nhttp://127.0.0.1:5000/"
        tkinter.messagebox.showinfo('成功','已开启服务！')
    else:
        tkinter.messagebox.showinfo('提示','服务已运行！')
    
def about():
    tkinter.messagebox.showinfo('帮助','图片GPS轨迹演示\n选择一个文件夹，自动遍历文件夹下的图片。\n将含有GPS信息的图片依照时间排序在地图显示轨迹。')

def connect():
    import webbrowser
    webbrowser.open("https://cxk-life.blog.csdn.net/")
    
def open_api_doc(event):
    import webbrowser
    webbrowser.open("http://127.0.0.1:5000/")

def exifImage(imageName):  #提取exif信息，若无则删除
    try:
        imageFile = open(imageName,'rb') 
        Info = exifread.process_file(imageFile) 
        if Info:
            for i,j in Info.items():
                # 纬度
                lat_ref = Info["GPS GPSLatitudeRef"].printable
                lat = Info["GPS GPSLatitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
                lat = float(lat[0]) + float(lat[1]) / 60 + float(lat[2]) / float(lat[3]) / 3600
                if lat_ref != "N":
                    lat = lat * (-1)
                # 经度
                lon_ref = Info["GPS GPSLongitudeRef"].printable
                lon = Info["GPS GPSLongitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
                lon = float(lon[0]) + float(lon[1]) / 60 + float(lon[2]) / float(lon[3]) / 3600
                if lon_ref != "E":
                    lon = lon * (-1)
                time = Info["EXIF DateTimeOriginal"].printable
                return time,lon,lat
    except KeyError:
            return None
            
def GetNameByEveryDir(file_dir):  
    # Input   Root Dir and get all img in per Dir.
    # Out     Every img with its filename and its dir and its path  
    FileNameWithPath = [] 
    FileName         = []
    FileDir          = []
    for root, dirs, files in os.walk(file_dir):  
        for file in files:  
            FileNameWithPath.append(os.path.join(root, file))  # 保存图片路径
            FileName.append(file)                              # 保存图片名称
            FileDir.append(root[len(file_dir):])               # 保存图片所在文件夹
    return FileName,FileNameWithPath,FileDir


if __name__ == '__main__':
    root=Tk()
    # 设置窗口大小
    winWidth = 600
    winHeight = 400
    # 获取屏幕分辨率
    screenWidth = root.winfo_screenwidth()
    screenHeight = root.winfo_screenheight()
    x = int((screenWidth - winWidth) / 2)
    y = int((screenHeight - winHeight) / 2)
    # 设置主窗口标题
    root.title("图片GPS轨迹演示")
    # 设置窗口初始位置在屏幕居中
    root.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))
    # 设置窗口图标
    root.iconbitmap("./img_gps_show/img/cxk.ico")
    # 设置窗口宽高固定
    root.resizable(0, 0)
    # 添加菜单栏
    f = tkinter.Menu(root)
    root['menu']=f
    f.add_command(label='关于',command=about)
    f.add_command(label='联系作者',command=connect)
    #增加背景图片
    photo = tk.PhotoImage(file="./img_gps_show/img/no_bg.png")
    theLabel = tk.Label(root,text="",justify=tk.LEFT,image=photo,compound = tk.CENTER)
    theLabel.place(relx=0.8, rely=0.63, anchor=CENTER)
    chiose=0
    Button(root,text='开启服务',command=start).place(relx=0.8, rely=0.08, anchor=CENTER)
    Button(root,text='输入文件夹\n（未开发）',command="#").place(relx=0.7, rely=0.2, anchor=CENTER)
    Button(root,text='打开文件所在\n（未开发）',command="#").place(relx=0.9, rely=0.2, anchor=CENTER)
    ft = tf.Font(family='微软雅黑',size=15)
    l=Label(root,font=ft)
    l.bind("<Button-1>",open_api_doc)
    l.place(relx=0.3, rely=0.5, anchor=CENTER)
    root.mainloop()
    # app.run(host='0.0.0.0',port=5000,debug=True,use_reloader=False)
